import { defineComponent, onMounted, type PropType, ref, toRefs } from 'vue'
import { Button, Card, Col, DatePicker, Form, FormItem, Input, Row, Select, Textarea } from 'ant-design-vue'
import { useDetail } from './use-detail'
import { useForm } from './use-form'
import { BusinessPageTypeEnum } from '@/enums/pageTypeEnum'
import { addressTypeObj, takeFinishStatus } from '@/views/task/task-publish/data'
import { optionsUser } from '@/api/system/user'

const props = {
  code: {
    type: [String, Number],
    required: false
  },
  businessType: {
    type: String as PropType<BusinessPageTypeEnum>,
    required: true,
    validator: (value: string) => {
      // 检查传入的值是否在枚举的有效值中
      return Object.values(BusinessPageTypeEnum).includes(value as BusinessPageTypeEnum)
    }
  }
}

const DataDetail = defineComponent({
  emits: ['cancelModal', 'confirmModal'],
  props,
  name: 'DataDetail',
  setup(props, ctx) {
    const { meta, state, initForm, getFormValues } = useForm()
    const { status, createOrUpdate, getDataById, getWarehouseList, getStoreOptions, getTagList } =
      useDetail(getFormValues)
    const addressOptionData = ref<any[]>([])
    const warehouseOptionData = ref<any[]>([])
    const storeOptionData = ref<any[]>([])
    const tagListData = ref<any[]>([])
    const executor = ref<any[]>([])
    const checkFormData = () => {
      if (!state.detailForm.name) {
        window.alert('任务名称')
        return false
      }
      const currentTime = new Date()
      let formattedTime = currentTime.getFullYear() + '-' + '-' + currentTime.getDate()
      if (currentTime.getMonth() + 1 < 10) {
        formattedTime += '0' + (currentTime.getMonth() + 1)
      } else {
        formattedTime += currentTime.getMonth() + 1
      }
      formattedTime += '-'
      if (currentTime.getDate() < 10) {
        formattedTime += '0' + currentTime.getDate()
      } else {
        formattedTime += currentTime.getDate()
      }
      if (state.detailForm.startTime != null && state.detailForm.deadline != null) {
        if (state.detailForm.startTime > state.detailForm.deadline) {
          window.alert('开始时间不能大于结束时间')
          return false
        }
        console.log(formattedTime, 9999999)
        if (state.detailForm.deadline < formattedTime) {
          window.alert('不能设置已完成时间')
          return false
        }
      }
      return true
    }

    const handleCommit = async () => {
      if (checkFormData()) {
        executor.value.forEach(item => {
          console.log(item, state.detailForm.executorCode)
          if (item.value === state.detailForm.executorCode) {
            state.detailForm.executorName = item.label
          }
        })
        await createOrUpdate()
        initForm()
        ctx.emit('confirmModal')
      }
    }

    const resetForm = () => {
      initForm()
      ctx.emit('cancelModal')
    }

    // 处理选择框的onChange事件
    const addressChange = value => {
      if (value == '1') {
        //仓库
        addressOptionData.value = warehouseOptionData.value
      } else if (value == '2') {
        //门店
        addressOptionData.value = storeOptionData.value
      }
      state.detailForm.addressCode = []
    }

    onMounted(async () => {
      await fetchData()
      warehouseOptionData.value = await getWarehouseList()
      storeOptionData.value = await getStoreOptions()
      if (state.detailForm.addressType === addressTypeObj[0].value) {
        addressOptionData.value = warehouseOptionData.value
      } else if (state.detailForm.addressType === addressTypeObj[1].value) {
        addressOptionData.value = storeOptionData.value
      }
      tagListData.value = await getTagList()
      executor.value = await optionsUser()
    })

    const fetchData = async () => {
      if (props.businessType === BusinessPageTypeEnum.UPDATE || props.businessType === BusinessPageTypeEnum.DETAIL) {
        // 查询值
        state.detailForm = await getDataById(props.code)
      }
    }

    return {
      ...toRefs(props),
      ...toRefs(state),
      ...toRefs(status),
      ...toRefs(meta),
      addressOptionData,
      warehouseOptionData,
      storeOptionData,
      tagListData,
      executor,
      addressChange,
      handleCommit,
      resetForm
    }
  },
  render() {
    const {
      businessType,
      detailForm,
      rules,
      addressOptionData,
      tagListData,
      executor,
      addressChange,
      handleCommit,
      resetForm
    } = this
    // @ts-ignore
    return (
      <>
        {detailForm && (
          <>
            <Card>
              <Form
                ref='detailFormRef'
                model={detailForm}
                rules={rules}
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 17 }}
                style={{ width: '80%' }}
                onFinish={handleCommit}
              >
                <FormItem label='任务名称' name='name'>
                  <Input
                    disabled={businessType !== BusinessPageTypeEnum.ADD}
                    v-model={[detailForm.name, 'value']}
                    maxLength={'20'}
                  />
                </FormItem>
                <FormItem label='执行位置类型' name='addressType'>
                  <Select
                    disabled={businessType !== BusinessPageTypeEnum.ADD}
                    mode='single'
                    v-model={[detailForm.addressType, 'value']}
                    options={addressTypeObj}
                    onChange={value => addressChange(value)}
                  />
                </FormItem>
                <FormItem label='执行位置' name='taskAddressFormList'>
                  <Select
                    disabled={businessType !== BusinessPageTypeEnum.ADD}
                    mode='multiple'
                    value={detailForm.taskAddressFormList
                      .filter(model => {
                        return model.taskAddressStatus && model.taskAddressStatus == takeFinishStatus[0].value
                      })
                      .map(model => {
                        return model.addressCode
                      })}
                    onChange={value =>
                      (detailForm.taskAddressFormList = value.map(model => {
                        return {
                          addressCode: model,
                          taskAddressStatus: 1
                        }
                      }))
                    }
                    options={addressOptionData}
                    placeholder={'请先选择执行位置类型'}
                  />
                </FormItem>
                <FormItem label='执行人' name='executeor'>
                  <Select
                    disabled={businessType !== BusinessPageTypeEnum.ADD}
                    v-model={[detailForm.executorCode, 'value']}
                    options={executor}
                  />
                </FormItem>
                <FormItem label='任务标签' name='tagVOList'>
                  <Select
                    disabled={businessType !== BusinessPageTypeEnum.ADD}
                    mode='multiple'
                    v-model={[detailForm.tagCodeList, 'value']}
                    options={tagListData}
                  />
                </FormItem>
                <FormItem label='已执行完位置' name='finishAddressCode'>
                  <Select
                    disabled={true}
                    mode='multiple'
                    value={detailForm.taskAddressFormList
                      .filter(model => {
                        return model.taskAddressStatus == takeFinishStatus[2].value
                      })
                      .map(model => {
                        return model.addressCode
                      })}
                    options={addressOptionData}
                  />
                </FormItem>
                <Row span={12}>
                  <Col span={12}>
                    <FormItem label='开始时间' name='startTime' labelCol={{ span: 6 }}>
                      <DatePicker
                        disabled={businessType !== BusinessPageTypeEnum.ADD}
                        v-model={[detailForm.startTime, 'value']}
                        valueFormat='YYYY-MM-DD'
                      />
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem label='结束时间' name='deadline' labelCol={{ offset: 1 }}>
                      <DatePicker
                        disabled={businessType !== BusinessPageTypeEnum.ADD}
                        v-model={[detailForm.deadline, 'value']}
                        valueFormat='YYYY-MM-DD'
                        //disabled-date="disabledDate"
                      />
                    </FormItem>
                  </Col>
                </Row>
                <FormItem label='具体描述' name='specificTask'>
                  <Textarea
                    disabled={businessType === BusinessPageTypeEnum.DETAIL && detailForm.status}
                    v-model={[detailForm.specificTask, 'value']}
                    maxlength={200}
                    rows={3}
                  />
                </FormItem>
                <FormItem wrapperCol={{ span: 12, offset: 12 }}>
                  {businessType === BusinessPageTypeEnum.DETAIL && <Button onClick={resetForm}>返回</Button>}
                  {businessType !== BusinessPageTypeEnum.DETAIL && (
                    <>
                      <Button type='primary' htmlType='submit'>
                        提交
                      </Button>
                      <Button style={{ marginLeft: '12px' }} onClick={resetForm}>
                        取消
                      </Button>
                    </>
                  )}
                </FormItem>
              </Form>
            </Card>
          </>
        )}
      </>
    )
  }
})

export default DataDetail
